package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.excel.model.StudentModel;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.service.impl
 */
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageResult<Student> pageQuery(StudentQueryParam studentQueryParam) {
        PageHelper.startPage(studentQueryParam.getPage(),studentQueryParam.getPageSize());
        Page<Student> pageInfo =studentMapper.pageQuery(studentQueryParam);
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getResult());
    }

    @Override
    public void add(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(student.getCreateTime());
        studentMapper.insert(student);
    }

    @Override
    public Student getById(Integer id) {
        return studentMapper.selectById(id);
    }

    @Override
    public void updateById(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.updateById(student);
    }

    @Override
    public void deleteById(Integer id) {
        studentMapper.deleteById(id);
    }

    @Override
    public void violation(Integer id, Integer score) {
        studentMapper.updateViolation(id,score);
    }

    @Override
    @Transactional
    public void importStudent(List<StudentModel> stuList, Integer clazzId) {
        /*for (StudentModel studentModel : stuList) {
            Student student = studentModel.toStudent(clazzId);
            studentMapper.insert(student);
        }*/
        //批量插入
        List<Student> studentList = stuList.stream().map(sm -> sm.toStudent(clazzId)).toList();
        studentMapper.insertBatch(studentList);
    }

    @Override
    public List<StudentModel> list(StudentQueryParam queryParam) {
        //查询数据库中的学员信息
        List<Student> students = studentMapper.pageQuery(queryParam);
        //把学员信息转成StudentModel对象
        List<StudentModel> studentModelList = students.stream().map(StudentModel::convert).collect(Collectors.toList());
        return studentModelList;
    }
}
